package me.zingon.service;

import me.zingon.dao.PackageDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Service
public class EmailService {
	@Autowired
	JavaMailSenderImpl mailSender;

	@Autowired
	ThreadPoolTaskExecutor taskExecutor;
	
	@Autowired
	PackageDao packageDao;

	@Autowired
	Properties msg;

	private void sendTo(String to,String content,String from,String subject){
		SimpleMailMessage message=new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(content);
		mailSender.send(message);
	}
	
	private void sendImg(String to,String content,String from,String subject,Resource r) throws MessagingException{
		MimeMessage message=mailSender.createMimeMessage();
		MimeMessageHelper helper=new MimeMessageHelper(message,true,"utf-8");
		helper.setFrom(from);
		helper.setTo(to);
		helper.setSubject(subject);
		if(r!=null) {
			helper.setText("<html><body><h1>"+ content+"</h1><img src='cid:img'></body></html>", true);
			helper.addInline("img", r);
		}else{
			helper.setText("<html><body>"+content+"</body></html>", true);
		}
		mailSender.send(message);
	}
	
	public void addTask(final String to,final String content,final int pId,final Resource r){
		taskExecutor.execute(new Runnable() {
			public void run() {
				// TODO Auto-generated method stub
				try {
					sendImg(to,content, msg.getProperty("mail.username"),msg.getProperty("mail.subject.package"),r);
				} catch (MessagingException e) {
					sendTo(to,content,msg.getProperty("mail.username"),msg.getProperty("mail.subject.package"));
					e.printStackTrace();
				}
				packageDao.setAdviced(pId);
			}
		});
	}

	public void sendActiveEmail(final String to,final String content,final Resource r){
		taskExecutor.execute(new Runnable() {
			public void run() {
				try {
					sendImg(to,content, msg.getProperty("mail.username"),msg.getProperty("mail.subject.active"),r);
				} catch (MessagingException e) {
					sendTo(to,content,msg.getProperty("mail.username"),msg.getProperty("mail.subject.active"));
					e.printStackTrace();
				}
			}
		});
	}
}
